package com.example.demo.controller.train;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.base.config.auth.UserInfoShareHolder;
import com.example.demo.base.login.dto.UserCache;
import com.example.demo.domain.entity.TrainClass;
import com.example.demo.domain.entity.TrainClassUser;
import com.example.demo.domain.entity.TrainCommitRecord;
import com.example.demo.domain.entity.TrainHomework;
import com.example.demo.domain.entity.TrainHomeworkProblem;
import com.example.demo.domain.entity.User;
import com.example.demo.domain.vo.HomeWorkDetailVo;
import com.example.demo.domain.vo.TrainClassUserVo;
import com.example.demo.dto.ResponseDto;
import com.example.demo.enums.TrainSubmitStatus;
import com.example.demo.param.TrainClassUserParam;
import com.example.demo.service.TrainClassService;
import com.example.demo.service.TrainClassUserService;
import com.example.demo.service.TrainCommitRecordService;
import com.example.demo.service.TrainHomeworkProblemService;
import com.example.demo.service.TrainHomeworkService;
import com.example.demo.service.UserService;
import com.example.demo.utils.BeanCopyUtil;
import com.example.demo.utils.CommonUtil;
import com.example.demo.utils.CopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liguang03
 * @date 2023/11/23
 */

/**
 * 培训模块-用户管理
 */
@Controller
@Slf4j
@RequestMapping("/train/train-class-user")
public class TrainClassUserController {


    @Resource
    private TrainClassService trainClassService;

    @Resource
    private TrainClassUserService trainClassUserService;


    @Resource
    private UserService userService;

    @Resource
    private TrainHomeworkService trainHomeworkService;

    @Resource
    private TrainHomeworkProblemService trainHomeworkProblemService;


    @Resource
    private TrainCommitRecordService trainCommitRecordService;


    /**
     * 获取培训班级所有的用户
     * @param
     * @return
     */
    @RequestMapping("/page-all-user")
    @ResponseBody
    public ResponseDto<Page<TrainClassUser>> getAllUserByPage(@RequestBody TrainClassUserParam param){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        TrainClass trainClass = trainClassService.getById(param.getTrainClassId());
        if (!userInfo.getCompanyId().equals(trainClass.getCompanyId())){
            return new ResponseDto<>().buildFail("无权限查看班级");
        }
        Page<TrainClassUser> page = trainClassUserService.queryByParam(param);
        return new ResponseDto<Page<TrainClassUser>>().buildSucceedHasData(page);
    }




    /**
     * 获取培训班级所有的用户
     * @param
     * @return
     */
    @RequestMapping("/all-user")
    @ResponseBody
    public ResponseDto<List<TrainClassUser>> getAllUser(Long trainClassId){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        TrainClass trainClass = trainClassService.getById(trainClassId);
        if (!userInfo.getCompanyId().equals(trainClass.getCompanyId())){
            return new ResponseDto<>().buildFail("无权限查看班级");
        }
        List<TrainClassUser> result = trainClassUserService.getAllUserByClassId(trainClassId);
        return new ResponseDto<List<TrainClassUser>>().buildSucceedHasData(result);
    }




    /**
     * 为某一个班级添加某一个用户
     * @param
     * @return
     */
    @RequestMapping("/add-user")
    @ResponseBody
    public ResponseDto<Boolean> addUserSingle(Long trainClassId, Long userId){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        TrainClass trainClass = trainClassService.getById(trainClassId);
        if (!userInfo.getCompanyId().equals(trainClass.getCompanyId())){
            return new ResponseDto<>().buildFail("无权限操作班级");
        }
        User user = userService.getById(userId);
        if (user == null) {
            return new ResponseDto<>().buildFail("用户不存在");
        }
        if (!userService.isIdentity(userId)){
            return new ResponseDto<>().buildFail("用户未实名，请先实名再添加");
        }
        TrainClassUser trainClassUser = trainClassUserService.queryByUserAndClass(trainClassId, userId);
        if (trainClassUser != null){
            return new ResponseDto<>().buildFail("用户已经在该班级中，无需重复添加");
        }
        TrainClassUser trainClassUserSave = new TrainClassUser();
        trainClassUserSave.setClassId(trainClass.getId());
        trainClassUserSave.setRealName(user.getRealName());
        trainClassUserSave.setUserId(userId);
        boolean save = trainClassUserService.save(trainClassUserSave);
        return new ResponseDto<Boolean>().buildSucceedHasData(save);
    }



    /**
     * 查询某一个用户所在的班级
     * @param
     * @return
     */
    @PostMapping("/user")
    @ResponseBody
    public ResponseDto<Page<TrainClassUserVo>> getUser(@Param("userId") String userId, @Param("pageNumber") Integer pageNumber, @Param("pageSize") Integer pageSize){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo == null){
            return new ResponseDto<>().buildFail("未登录");
        }
        boolean isFalseInput = true;
        Page<TrainClassUserVo> result = new Page<>();
        if(userId.matches("^[0-9]+$")){
            TrainClassUser user = trainClassUserService.getById(Long.valueOf(userId));
            if (user == null) {
                return new ResponseDto<>().buildFail("用户不存在");
            }
            Page<TrainClass> classPage = trainClassUserService.queryClassByUserId(Long.valueOf(userId), pageNumber, pageSize);
            if(classPage.getTotal() != 0){
                result.setCurrent(classPage.getCurrent());
                result.setTotal(classPage.getTotal());
                result.setSize(classPage.getSize());
                List<TrainClassUserVo> trainClassUserVos = BeanCopyUtil.copyListProperties(classPage.getRecords(), TrainClassUserVo::new);
                trainClassUserVos.forEach(trainClassUserVo -> {
                    trainClassUserVo.setRealName(user.getRealName());
                });
                result.setRecords(trainClassUserVos);
                isFalseInput = false;
            }
        }else {
            List<TrainClassUser> user = trainClassUserService.getBaseMapper().selectList(new LambdaQueryWrapper<TrainClassUser>().eq(TrainClassUser::getRealName,userId));
            if (user == null) {
                return new ResponseDto<>().buildFail("用户不存在");
            }
            Page<TrainClass> classPageByRealName = trainClassUserService.queryClassByRealName(userId, pageNumber, pageSize);
            if(classPageByRealName.getTotal() != 0){
                result.setCurrent(classPageByRealName.getCurrent());
                result.setTotal(classPageByRealName.getTotal());
                result.setSize(classPageByRealName.getSize());
                List<TrainClassUserVo> trainClassUserVos = BeanCopyUtil.copyListProperties(classPageByRealName.getRecords(), TrainClassUserVo::new);
                trainClassUserVos.forEach(trainClassUserVo -> {
                    trainClassUserVo.setRealName(userId);
                });
                result.setRecords(trainClassUserVos);
                isFalseInput = false;
            }
        }
        if(isFalseInput) {
            return new ResponseDto().buildSucceedHasData(result);
        }
        return new ResponseDto().buildSucceedHasData(result);
    }



    /**
     * 查询某一个用户某个班级的作业记录
     * homeworkId 可不传
     * @param
     * @return
     */
    @RequestMapping("/user/class-homework")
    @ResponseBody
    public ResponseDto<Page<HomeWorkDetailVo>> userClassHomeWork(TrainClassUserParam param ){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo == null){
            return new ResponseDto<>().buildFail("未登录");
        }
        TrainClass trainClass = trainClassService.getById(param.getTrainClassId());
        if (trainClass == null){
            return new ResponseDto<>().buildFail("班级不存在");
        }
        Page<TrainHomework> assignedHomeWorkForClass = trainHomeworkService.getAssignedHomeWorkForClass(param);
        if (assignedHomeWorkForClass.getTotal() == 0){
            return new ResponseDto().buildSucceed();
        }
        //目前是一个作业一题，交互就没啥问题
        Page<HomeWorkDetailVo> result = new Page<>();
        result.setCurrent(assignedHomeWorkForClass.getCurrent());
        result.setSize(assignedHomeWorkForClass.getSize());
        result.setTotal(assignedHomeWorkForClass.getTotal());
        List<TrainHomework> records = assignedHomeWorkForClass.getRecords();
        List<HomeWorkDetailVo> homeWorkDetailVos = BeanCopyUtil.copyListProperties(records, HomeWorkDetailVo::new);
        result.setRecords(homeWorkDetailVos);
        List<Long> homeworkIds = records.stream().map(TrainHomework::getId).collect(Collectors.toList());
        List<TrainHomeworkProblem> trainHomeworkProblems = trainHomeworkProblemService.queryByHwIds(homeworkIds);
        Map<Long, TrainHomeworkProblem> map = trainHomeworkProblems.stream().collect(Collectors.toMap(TrainHomeworkProblem::getHomeworkId, o -> o, (a, b) -> b));

        for (HomeWorkDetailVo homeWorkDetailVo : homeWorkDetailVos) {
            Long homeWorkId = homeWorkDetailVo.getId();
            TrainHomeworkProblem trainHomeworkProblem = map.get(homeWorkId);
            if (trainHomeworkProblem == null){
                continue;
            }
            List<TrainCommitRecord> trainCommitRecords = trainCommitRecordService.queryByHwIdAndPIdAndClassIdAndUser(homeWorkId, trainHomeworkProblem.getProblemId(), param.getTrainClassId(), param.getUserId());
            if (CollectionUtils.isEmpty(trainCommitRecords)){
                continue;
            }
            trainCommitRecords.sort(Comparator.comparing(TrainCommitRecord::getSubmitTime, Comparator.reverseOrder()));
            int size = trainCommitRecords.stream().filter(trainCommitRecord -> CommonUtil.isNotNullId(trainCommitRecord.getSubmitId())).collect(Collectors.toList()).size();
            TrainCommitRecord record = trainCommitRecords.get(0);
            homeWorkDetailVo.setLastSubmitId(record.getSubmitId());
            homeWorkDetailVo.setSubmitStatus(record.getSubmitTime() == null ? TrainSubmitStatus.NOT_SUBMIT.getKey() : TrainSubmitStatus.SUBMIT.getKey());
            homeWorkDetailVo.setScore(record.getScore());
            homeWorkDetailVo.setSubmitTimes(size);
            homeWorkDetailVo.setSubmitTime(record.getSubmitTime());
        }
        return new ResponseDto().buildSucceedHasData(result);
    }



































}
